<?php
/**
 * Atlas KOTASOFT cakephp
 *
 * Bakes web interface 
 *
 * PHP versions 4 and 5
 *
 * ATLAS KOTASOFT  cakephp web code generator
 * Copyright 2009, Kotasoft agile factory, Inc. (http://www.atlascakephp.com)
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @filesource
 * @copyright     Copyright 2009, Kotasoft agile factory , Inc. (http://www.kotasoft.com)
 * @link          http://www.atlascakephp.com  ATLAS KOTASOFT Project
 * @version       BETA 0.5 $
 * @modifiedby    $LastChangedBy: daniel castanera - guldoe and francisco dominguez - idioto $
 * @license       http://www.opensource.org/licenses/mit-license.php The MIT License
 */

require ("kt_app_controller.php");

/* class KtviewsController, generate views  */
class KtviewsController extends KtAppController {
 	var $helpers = array('Html', 'Form', 'Javascript'); 
 	//var $path = "";
 	var $ruta_admin = "/admin/ktviews/";
 	var $controllerName="";
 	var $userDbConfig="";
 	
 	var $fields;
 	
 	/* index for admin, get tables from database */
 	function admin_index(){	  
	  $session=$this->Session->read(KT_SESSION); 
 	  $this->set("configuration",$session['Ktconfiguration']);  
 	  
 	  if (isset($session['Ktconfiguration']['url']) && $session['Ktconfiguration']['url']!= " " ){
 	  	$this->set('url_route',$session['Ktconfiguration']['url']);
 	  }    
	  // select bd configuration 
	  if(!$this->__dbConfig()){
	      $this->Session->setFlash(__('Your configuration is not available',true));	
	      $this->log(__('Your configuration is not available',true), LOG_DEBUG);		 	
	  }
		 
	  
	  if (!empty($this->data)) {	  	 
			$this->userDbConfig=$this->data['Ktview']['selectedbd'];
	  }else if (count($session['Ktconfiguration'])>0){      
	  		$this->userDbConfig = $session['Ktconfiguration']['name'];
        
	  }
	  	
	  $useDbConfig=$this->userDbConfig;
	  if ($useDbConfig!=""){
					$this->set('configName',$this->data['Ktview']['selectedbd']);	   
					$this->set('ruta_admin',$this->ruta_admin);	   
					
					$tables=$this->listAll($useDbConfig);
					$tables_controller	 =$this->__tables_with_controller($tables);	
					$tables_no_controller=$this->__tables_without_controller($tables);	
					
					if(count($tables_controller) > 0){
						$this->set('tables', $tables_controller); 		
					} else {
						$this->set('tables', array()); 	
					}
					if(count($tables_no_controller) > 0) {
						$this->set('tables_no_controller',$tables_no_controller);	
					} else	{
						$this->set('tables_no_controller',array());	
					}
	  } else {
				$this->Session->setFlash(__('Your database not have tables available',true));	
				$this->log(__('Your database not have tables available',true), LOG_DEBUG);		
		}
     }
    
	

	/* Return a Array with each tables that have a model created */
	function __tables_with_controller($tables)
	{	$out = array();
		$nTables=count($tables);
		$config_Controllerdir=$this->viewVars["configuration"]["directory"].DS."app".DS."controllers".DS;
	 	foreach($tables as $table)
	 	{
	 		if(file_exists($config_Controllerdir.$table."_controller.php"))
	 			$out[]=$table;	
	 	}
	 	return $out;
	}

	/* Return a Array with each tables that have not a model created */
	function __tables_without_controller($tables)
	{	$out = array();
		$nTables=count($tables);
		$config_Controllerdir=$this->viewVars["configuration"]["directory"].DS."app".DS."controllers".DS;
	 	$out = array();
		foreach($tables as $table)
	 	{
	 		if(!file_exists($config_Controllerdir.$table."_controller.php"))
	 			$out[]=$table;	
	 	}
	 	return $out;
	}		
	
	/*  admin generate, render file with configuration for views */
    function admin_generate($names=null) {
    	
		$session=$this->Session->read(KT_SESSION); 			
		$this->userDbConfig=$session['Ktconfiguration']["name"]; 	
	    $this->set("userDbConfig",$this->userDbConfig);	    
 	    $this->set("configuration",$session['Ktconfiguration']); 
 	    $this->set("selected_view",$names);
 	    
 	    $this->set("name",$names);	 
 	    $this->__model_results($this->userDbConfig,$names); 
 	     
	    if(!$this->__checkDirectoryProject()){
 	    		$this->Session->setFlash(__('Error directory configuration, files not could be created, check configuration',true));
 	    		$this->log(__('Error directory configuration, files not could be created, check configuration',true), LOG_DEBUG);		
 	    		$this->redirect("/admin/ktconfigurations");	
 	    }   
	  
 	    
 	    
	}
	
    /* return array of fields to configure*/
 	function __model_results($configName,$names){
 		        
      	 $model = new Model("",$names,$configName);      	
      	 if (is_object($model)) {
      	 	$primaryKey = $model->primaryKey;
			$useTable = $model->table;
			$useDbConfig = $configName;			
			$name = $model->name;
      	 }
      	 
      	 $fields = $this->__doFields($model,true);
      	 
		 foreach ($fields as $field => $value) {	
		 		if ($field!="id")	           
		          $array[]= array("name" => $field, "type" => $value["type"]);		
		 }
      	 
		 $this->set("fields",$array); 

		 $options_ = array('input' => 'input', 'password' => 'password', 'checkbox' => 'checkbox', 'textarea' => 'textarea', 'select' => 'select',);
         $this->set("selector",$options_);        
      }
    
    
       /* render files */ 
      function admin_norender($names=null) {
      	
      	// read session configuration
      	$session=$this->Session->read(KT_SESSION); 			
		$this->userDbConfig=$session['Ktconfiguration']["name"];		
		
		// set render layout
		$this->layout ='render_layout';
		
        $mensaje = $this->__checkDirectory();	    
	    if ($mensaje!=""){
	    	$this->Session->setFlash(__($mensaje,true));	
	    	$this->redirect(array('action' => 'admin_index'));
	    }
	    // if have datas from form	     
		if (!empty($this->data)){
			$this->controllerName = $this->data['Ktview']['selected_view'];
			if($this->__generateFields()==true){
				$this->Session->setFlash(__('the methods you choose, are generate',true));
				$this->log(__('the methods you choose, are generate',true), LOG_DEBUG);		
 	    	
			} else {
				$this->log(__('no generate files in view, select almost one method',true), LOG_DEBUG);	
				$this->Session->setFlash(__('no generate files in view, select almost one method',true));
			}
		}	
		$this->redirect(array('action' => 'admin_index'));	
      }
    
    
    /* generate views from configurations */
	function __generateFields()	{
				
		$options = $this->data['Ktview']['usercheck'];
		$flag_generate = false;
		$this->fields = $this->data['Ktview']['valid'];
		// check for index
		if($options["index"] == 1) {
			//$this->__generateLinkHome("index");
			$this->__generateView("index");
			$flag_generate = true;
		}
		
		// check for add
		if($options["add"] == 1) {
			$this->__generateView("add");	
			$flag_generate = true;
		}
		
		// check for view
		if($options["view"] == 1) {
			$this->__generateView("view");	
			$flag_generate = true;
		}
		
		// check for edit
		if($options["edit"] == 1) {
			$this->__generateView("edit");
			$flag_generate = true;		
		}
		
		// selected admins configurations
		$options = $this->data['Ktview']['admincheck'];
		
		// check for admin index
		if($options["index"] == 1) {
			$this->__generateView("index",1);
			$flag_generate = true;
		}
		
		// check for admin add	
		if($options["add"] == 1) {
			$this->__generateView("add",1);	
			$flag_generate = true;
		}
		
		// check for admin view	
		if($options["view"] == 1) {
			$this->__generateView("view",1);
			$flag_generate = true;	
		}
		
		// check for admin edit	
		if($options["edit"] == 1) {
			$this->__generateView("edit",1);
			$flag_generate = true;
		}		
		return $flag_generate;
	}    
	
	 
	
	/**
	 *  generate view selected  
	 *  params $_view  is type of view , index, add, ..
	 *  params $admin  boolean 
	 */ 
	function __generateView($_view,$admin=0)
	{
		$this->set("pluralVar",Inflector::variable($this->controllerName));
		$currentControllerName = $this->_modelName($this->controllerName);
		
		$singularName = Inflector::variable($currentControllerName);
		$pluralName =$this->_pluralName($currentControllerName);
		

		$output=file_get_contents(dirname(__FILE__)."/../views/ktviews/__".$_view.".ctp");		
		$output=str_replace('$pluralName_uc'	,ucwords($pluralName)		,$output);
		$output=str_replace('$pluralName'		,$pluralName				,$output);
		$output=str_replace('$singularName_uc'	,ucwords($singularName)		,$output);
		$output=str_replace('$singularName'		,$singularName				,$output);
		
		$output=$this->__get_formInputs($output);
		$output=$this->__get_data_view($output,$singularName);
		$output=$this->__get_data_index($output,$singularName);

		$session = $this->Session->read(KT_SESSION);
  		$path = $session[KT_CONFIGURATION][KT_DIRECTORY]."/app/views".DS.$pluralName.DS; 	

		$filename = $path .$_view.'.ctp'; 
		if($admin==1)
			$filename=$path .'admin_'.$_view.'.ctp'; 

  		if($this->createFile($filename, $output))
  		{
			$this->Session->setFlash("'".$_view."' creado con exito");
    			$this->log(__("'".$_view."' creado con exito",true), LOG_DEBUG);	
			
  		}
  		else
  		{   $this->log(__("No se ha podido crear el fichero '".$_view."'",true), LOG_DEBUG);	
			$this->Session->setFlash("No se ha podido crear el fichero '".$_view."'");
    		//$this->redirect(array('action' => 'admin_index'));
  		}		
	}
	
	function __get_formInputs($output) {
		//TODO arreglar esto esta to guarro	
		$formInputs=""; 		
 		$fields = $this->fields;
 		$cont=1;
		 foreach ($fields as $field => $value) {		 	     
				if($field!="id")	
					if ($value=="select") {
						$formInputs.=  $this->__getType($field,$value,$cont);
						$cont++;
					} else {				
						$formInputs.=  $this->__getType($field,$value);
					}
				
		 }
		$output=str_replace('$formInputs',$formInputs,$output);	
		return $output;
	}

	
	
	function __getType($field,$value,$cont="") {
		$output="";
		 // echo "<pre>"; print_r($field. " -- ". $value . "--" . $cont); echo "</pre>";
		$selector_info="";
		switch($value){		 
			case "password":
				 $output = "\n\t\t".'echo $form->label("'.$field.'");';
				$output .= "\n\t\t".'echo $form->password("'.$field.'");';
			break;
			
			case "textarea":
				 $output = "\n\t\t".'echo $form->label("'.$field.'");';
				$output .= "\n\t\t".'echo $form->textarea("'.$field.'");';
			break;
			
			case "checkbox":
				$output = "\n\t\t".'echo $form->label("'.$field.'");';
				$output .= "\n\t\t".'echo $form->checkbox("'.$field.'");';
			break;
			
			case "select":
				$output = "\n\t\t".'echo $form->label("'.$field.'");';
				$output .= "\n\t\t".'echo $form->select("'.$field.'",$selector_info'.$cont.');';
			break;
			
			case "input":
			default:
				$output .= "\n\t\t".'echo $form->input("'.$field.'");';
			break;
		}
		return $output;
	}
	
	
	function __doFields(&$model, $interactive = true) {
		if (!is_object($model)) {
			return false;
		}
		$fields = $model->schema();
		return $fields;
		
	}
	
	function __get_data_view($output,$singularName)	{
		$data_view="";
		
 		$fields = $this->__get_db_fields();
		foreach ($fields as $field => $value)	
		{
			$data_view .='
			<dt<?php if ($i % 2 == 0) echo $class;?>><?php __("'.ucwords($field).'"); ?></dt>
			<dd<?php if ($i++ % 2 == 0) echo $class;?>>
				<?php echo $'.$singularName.'["'.ucwords($singularName).'"]["'.$field.'"]; ?>
				&nbsp;
			</dd>';	
		}	
		$output=str_replace('$data_view',$data_view,$output);
		return $output;
	}
	
	function __get_data_index($output,$singularName) {
		$data_index_titles="";
		$data_index="";
      	 
      	 $fields = $this->__get_db_fields();
      	 
		 foreach ($fields as $field => $value)
		 {		           
			$data_index_titles .="\n\t\t".'<th><?php echo $paginator->sort("'.$field.'");?></th>';
			$data_index .="		
			<td>
				<?php echo $".$singularName."['".ucwords($singularName)."']['".$field."']; ?>
			</td>";		
		 }
		$output=str_replace('$data_index_titles'		,$data_index_titles	,$output);
		$output=str_replace('$data_index'				,$data_index		,$output);
		return $output;	
	}
	
	function __get_db_fields()	{
		
		$aux=$this->_pluralName($this->data["Ktview"]["selected_view"]);

		$configName=$this->userDbConfig;
		$names=$aux;
      	$model = new Model("",$names,$configName);
      	
      	 if (is_object($model)){
      	 	$primaryKey = $model->primaryKey;
			$useTable = $model->table;
			$useDbConfig = $configName;			
			$name = $model->name;
      	 }		
		return $this->__doFields($model,true);
	}
	
	function __generateLinkHome($action)
	{
		$atlas_content="";
		$file=$_SESSION[KT_SESSION]["Ktconfiguration"]["directory"].DS."app".DS."views".DS."layouts".DS."default.ctp";
		$file_copy= file_get_contents($file);
		$useDbConfig=$_SESSION[KT_SESSION]["Ktconfiguration"]["name"];
		
		$currentControllerName = $this->_modelName($this->controllerName);
		$link="./".$this->_pluralName($currentControllerName).'/'.$action;

		$token='<!-- token info atlas --><br>';
		$atlas_content .='<a href="'.$link.'">'.$currentControllerName."->".$action.'</a>';
		
		$file_copy=str_replace($token,($atlas_content.$token),$file_copy);

		$fp = fopen($this->__output . $file, 'w');
		fwrite($fp,$file_copy);
		fclose($fp);	
	}
}
?>